from PORTSets import *
from UARTDevice import UARTDevice
from USBDevice import USBDevice
from CMDSetsDevice import DeviceCmdSetsController
from CMDSets import *

__ALL_DEVICE_CONTROLLER={}

def get_port(identifier):
    if identifier and identifier in __ALL_DEVICE_CONTROLLER:
        return __ALL_DEVICE_CONTROLLER[identifier]
    return None

def set_port(identifier,device):
    __ALL_DEVICE_CONTROLLER[identifier] = device

def del_port(identifier):
    if identifier and identifier in __ALL_DEVICE_CONTROLLER:
        del __ALL_DEVICE_CONTROLLER[identifier]
    __ALL_DEVICE_CONTROLLER[identifier]=None

def check_port():
    print(__ALL_DEVICE_CONTROLLER)

def __split_cmdsets(cmdextends):
    basic_cmd_extends = {}
    more_cmd_entends = []
    if cmdextends is None:
        return basic_cmd_extends,more_cmd_entends
    if isinstance(cmdextends,list):
        if len(cmdextends)>0:
            basic_cmd_extends = cmdextends[0]
        if len(cmdextends)>1:
            more_cmd_entends = cmdextends[1:]
    else:
        basic_cmd_extends = cmdextends
    return basic_cmd_extends,more_cmd_entends

def connect_all_uart_device(logger,cmdextends=None):
    basic_cmd_extends, more_cmd_entends = __split_cmdsets(cmdextends)
    for identifier,_path in UART_PATHs.items():
        _device = UARTDevice(_path, logger, 230400, 5)
        _port = DeviceCmdSetsController(_device,cmdextends=basic_cmd_extends,identifier=identifier,defaultAction='sendAndRead')
        for _cmdextends in more_cmd_entends:
            _port.check_instruction_set(_cmdextends)
        set_port(identifier,_port)

def connect_all_usb_device(logger,cmdextends):
    basic_cmd_extends, more_cmd_entends = __split_cmdsets(cmdextends)
    for identifier,_path in USB_PATHs.items():
        _device = USBDevice(_path, logger)
        _port = DeviceCmdSetsController(_device,cmdextends=basic_cmd_extends,identifier=identifier,defaultAction='write')
        for _cmdextends in more_cmd_entends:
            _port.check_instruction_set(_cmdextends)
        set_port(identifier,_port)

def connect_devices(logger,uart_cmdsets=[],usb_cmdsets=[]):
    connect_all_uart_device(logger, uart_cmdsets)
    connect_all_usb_device(logger, usb_cmdsets)

def get_device(identifier):
    _port = get_port(identifier)
    if _port:
        return _port['device']
    return None

def list_device():
    print(UARTDevice.list_device())
    print(USBDevice.list_device())



